package seller

import (
	"dhfshop/models/seller"
	"time"
	"encoding/json"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type FreightController struct {
	base.BaseController
}

func (this *FreightController) List() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := seller.GetAllFreightRules(query,order_by,fields,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	} else {
		r := struct {
		    TotalCount   int64                 `json:"total_count"`
	        FreightRule  []*seller.FreightRule `json:"freight_rule"`
	    }{TotalCount: cnt, FreightRule: l}
	    this.Data["json"] = r
	}
	this.ServeJSON()
}

func (this *FreightController) Post() {
	var v seller.FreightRule
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if v.FreightRuleId == 0 {    //add freight rule
		ruleId, err := seller.AddFreightRule(&v)
		if err != nil {
			beego.Debug("err:", err.Error())
			this.ServeError(err.Error())
			return
		}
		v.FreightRuleId = ruleId
		if len(v.DistanceJson) > 0 {
			beego.Debug("v.DistanceJson:", v.DistanceJson)
			
			err := json.Unmarshal([]byte(v.DistanceJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.DistanceFees {
				item.FreightRule = &v               
			}
			if err := seller.AddMulDistanceFees(v.DistanceFees); err != nil {
				beego.Debug("err:", err.Error())
				this.ServeError(err.Error())
				return
			}
	    }
		if len(v.WeightJson) > 0 {
			beego.Debug("v.WeightJson:", v.WeightJson)
			err := json.Unmarshal([]byte(v.WeightJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.WeightFees {
				item.FreightRule = &v               
			}
			if err := seller.AddMulWeightFees(v.WeightFees); err != nil {
				beego.Debug("err:", err.Error())
				this.ServeError(err.Error())
				return
			}
	    }
		if len(v.PeriodJson) > 0 {
			beego.Debug("v.PeriodJson:", v.PeriodJson)
			err := json.Unmarshal([]byte(v.PeriodJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.PeriodFees {
				item.FreightRule = &v               
			}
			if err := seller.AddMulPeriodFees(v.PeriodFees); err != nil {
				beego.Debug("err:", err.Error())
				this.ServeError(err.Error())
				return
			}
	    }
	}else{                                 // add freight sub_item
		oldFreight, err := seller.GetFreightRuleById(v.FreightRuleId)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		if len(v.DistanceJson) > 0 {
			err := json.Unmarshal([]byte(v.DistanceJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.DistanceFees {
				item.FreightRule = oldFreight               
			}
			if err := seller.AddMulDistanceFees(v.DistanceFees); err != nil {
				beego.Debug("err:", err.Error())
				this.ServeError(err.Error())
				return
			}
	    }
		if len(v.WeightJson) > 0 {
			err := json.Unmarshal([]byte(v.WeightJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.WeightFees {
				item.FreightRule = oldFreight               
			}
			if err := seller.AddMulWeightFees(v.WeightFees); err != nil {
				beego.Debug("err:", err.Error())
				this.ServeError(err.Error())
				return
			}
	    }
		if len(v.PeriodJson) > 0 {
			err := json.Unmarshal([]byte(v.PeriodJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.PeriodFees {
				item.FreightRule = oldFreight               
			}
			if err := seller.AddMulPeriodFees(v.PeriodFees); err != nil {
				beego.Debug("err:", err.Error())
				this.ServeError(err.Error())
				return
			}
	    }	
	}
	rsp := struct {
		FreightRuleId int64      `json:"freight_rule_id"`
	    Created       time.Time  `json:"created"`
	}{FreightRuleId: v.FreightRuleId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *FreightController) Put() {
	var v seller.FreightRule
	this.ParseForm(&v)  
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	excludeArr := []string{"freight_rule_id","partner_id","store_id","distance_fees","weight_fees","period_fees"}
	updateFields, err := this.GetUpdateFields(v, "", "form", excludeArr)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err := seller.UpdateFreightRuleById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	if len(v.DistanceJson) > 0 {
		err := json.Unmarshal([]byte(v.DistanceJson), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, item := range v.DistanceFees {
			updateFields := []string{}
	        if item.No > 0 {
		       updateFields = append(updateFields, "no")
	        }
			if item.Lower > 0 {
		       updateFields = append(updateFields, "lower")
	        }
			if item.Upper > 0 {
		       updateFields = append(updateFields, "upper")
	        }
			if item.Unit > 0 {
		       updateFields = append(updateFields, "unit")
	        }
			if item.UnitFee > 0 {
		       updateFields = append(updateFields, "unit_fee")
	        }
			seller.UpdateDistanceFee(item, updateFields...)            
		}
	}
	if len(v.WeightJson) > 0 {
		err := json.Unmarshal([]byte(v.WeightJson), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, item := range v.WeightFees {
			updateFields := []string{}
	        if item.No > 0 {
		       updateFields = append(updateFields, "no")
	        }
			if item.Lower > 0 {
		       updateFields = append(updateFields, "lower")
	        }
			if item.Upper > 0 {
		       updateFields = append(updateFields, "upper")
	        }
			if item.Unit > 0 {
		       updateFields = append(updateFields, "unit")
	        }
			if item.UnitFee > 0 {
		       updateFields = append(updateFields, "unit_fee")
	        }
			seller.UpdateWeightFee(item, updateFields...)            
		}
	}
	if len(v.PeriodJson) > 0 {
		err := json.Unmarshal([]byte(v.PeriodJson), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, item := range v.PeriodFees {
			updateFields := []string{}
	        if item.No > 0 {
		       updateFields = append(updateFields, "no")
	        }
			if len(item.Start) > 0 {
		       updateFields = append(updateFields, "start")
	        }
			if len(item.End) > 0 {
		       updateFields = append(updateFields, "end")
	        }
			if item.UnitFee > 0 {
		       updateFields = append(updateFields, "unit_fee")
	        }
			seller.UpdatePeriodFee(item, updateFields...)            
		}
	}
	rsp := struct {
		FreightRuleId int64      `json:"freight_rule_id"`
	    Modified      time.Time  `json:"modified"`
	}{FreightRuleId:v.FreightRuleId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *FreightController) Delete() {
	var v seller.FreightRule
	this.ParseForm(&v)  
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if v.FreightRuleId > 0 {
	    if err := seller.DeleteFreightRule(v.FreightRuleId); err != nil {   
	        this.ServeError(err.Error())
		    return
	    }
	}
	if len(v.DistanceJson) > 0 {
		err := json.Unmarshal([]byte(v.DistanceJson), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, item := range v.DistanceFees {
		    seller.DeleteDistanceFee(item.DistanceFeeId)
		}
	}
	if len(v.WeightJson) > 0 {
		err := json.Unmarshal([]byte(v.WeightJson), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, item := range v.WeightFees {
		    seller.DeleteWeightFee(item.WeightFeeId)
		}
	}
	if len(v.PeriodJson) > 0 {
		err := json.Unmarshal([]byte(v.PeriodJson), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, item := range v.PeriodFees {
		    seller.DeletePeriodFee(item.PeriodFeeId)
		}
	}
	rsp := struct {
		FreightRuleId int64     `json:"freight_rule_id"`
		Modified      time.Time `json:"modified"`
	}{FreightRuleId:v.FreightRuleId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
